package com.hwg.emp.web.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hwg.emp.common.exception.EmpException;
import com.hwg.emp.common.util.DBUtil;
import com.hwg.emp.model.DeptMD;
import com.hwg.emp.model.UserMD;
import com.hwg.emp.service.DeptService;
import com.hwg.emp.service.ServiceFactroy;
import com.hwg.emp.service.UserService;

public class AddDeptController extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		try{
			req.setCharacterEncoding("utf-8");
			resp.setCharacterEncoding("utf-8");
			UserService userService = ServiceFactroy.getService(UserService.class);
			DeptService deptService = ServiceFactroy.getService(DeptService.class);
			String name = req.getParameter("name");
			String account = req.getParameter("manager");
			String remark = req.getParameter("remark");
			req.setAttribute("name", name);
			req.setAttribute("manager", account);
			req.setAttribute("remark", remark);
			DeptMD deptMD = new DeptMD();
			deptMD.setId(DBUtil.uuid());
			deptMD.setName(name);
			deptMD.setRemark(remark);
			UserMD user = new UserMD();
			user.setAccount(account);
			deptMD.setManager(user);
			boolean flag = deptService.addDept(deptMD);
			if(flag){
				req.getRequestDispatcher("/selectDepts.do").forward(req, resp);
				return;
			}
		} catch (EmpException e) {
			req.setAttribute("message", e.getMessage());
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
			req.setAttribute("message", "系统繁忙,请稍后再试!");
		}
		req.getRequestDispatcher("/pages/addDept.jsp").forward(req, resp);
	}
	
}
